package weishu.me.hookaudiotrack;

import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import weishu.me.hookaudio.AudioController;

public class MainActivity extends Activity {

    private static final String TAG = "MainActivity";

    Button hook, test;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        hook = findViewById(R.id.hook);
        test = findViewById(R.id.test);

        hook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AudioController.muteMode(Build.VERSION.SDK_INT);
            }
        });

        test.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    testWriteByte();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void testWriteByte() throws Exception {
        // constants for test
        final String TEST_NAME = "testWriteByte";
        final int TEST_SR = 22050;
        final int TEST_CONF = AudioFormat.CHANNEL_OUT_MONO;
        final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
        final int TEST_MODE = AudioTrack.MODE_STREAM;
        final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;

        //-------- initialization --------------
        int minBuffSize = AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT);
        AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT,
                2*minBuffSize, TEST_MODE);
        byte data[] = new byte[minBuffSize];
        //--------    test        --------------
        assumeTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED);
        // assumeTrue(TEST_NAME, track.write(data, 0, data.length) == data.length);

        int ret = track.write(data, 0, data.length);


        Log.i(TAG, "ret: " + ret + " data length : " + data.length);

        //-------- tear down      --------------
        track.release();
    }

    private static void assumeTrue(String name, boolean condition) {
        if (!condition) {
            Log.e(TAG, "error: " + name);
        }
    }
}
